package com.saint.lt.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.saint.lt.domain.User;

@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void add(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@Override
	public void remove(User user) {
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}

	}

	@Override
	public void remove(String username) {
		User user = (User) sessionFactory.getCurrentSession().load(User.class,
				username);
		remove(user);
	}

	@Override
	public List<User> list() {
		List<User> users = sessionFactory.getCurrentSession().createCriteria(User.class).list();
//		if (null == users) {
//			users = new ArrayList<User>();
//		}
		return users;
	}

	@Override
	public User get(String username) {
		Criteria cr = sessionFactory.getCurrentSession().createCriteria(User.class);
		cr.add(Restrictions.eq("username", username));
		User result = (User) cr.uniqueResult();
		return result;
	}

}
